package com.lushuai.jiubeidanci.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "jiubei.db";
    private static final int DATABASE_VERSION = 1;

    // 用户表
    public static final String TABLE_USERS = "users";
    
    // 用户表字段
    public static final String COLUMN_USER_ID = "user_id";
    public static final String COLUMN_NICKNAME = "nickname";
    public static final String COLUMN_PASSWORD = "password";
    public static final String COLUMN_AVATAR_URL = "avatar_url";
    public static final String COLUMN_IS_VIP = "is_vip";
    public static final String COLUMN_COINS = "coins";
    public static final String COLUMN_EQUIPMENT_COUNT = "equipment_count";
    public static final String COLUMN_EMAIL = "email";
    public static final String COLUMN_PHONE = "phone";
    public static final String COLUMN_CREATE_TIME = "create_time";
    public static final String COLUMN_LAST_LOGIN_TIME = "last_login_time";

    // 创建用户表的SQL语句
    private static final String CREATE_TABLE_USERS = 
        "CREATE TABLE " + TABLE_USERS + " (" +
        COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        COLUMN_NICKNAME + " TEXT NOT NULL, " +
        COLUMN_PASSWORD + " TEXT NOT NULL, " +
        COLUMN_AVATAR_URL + " TEXT, " +
        COLUMN_IS_VIP + " INTEGER DEFAULT 0, " +
        COLUMN_COINS + " INTEGER DEFAULT 0, " +
        COLUMN_EQUIPMENT_COUNT + " INTEGER DEFAULT 0, " +
        COLUMN_EMAIL + " TEXT, " +
        COLUMN_PHONE + " TEXT, " +
        COLUMN_CREATE_TIME + " INTEGER, " +
        COLUMN_LAST_LOGIN_TIME + " INTEGER" +
        ")";

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建用户表
        db.execSQL(CREATE_TABLE_USERS);
        
        // 插入默认管理员账户
        insertDefaultAdmin(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 升级数据库时删除旧表并创建新表
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
        onCreate(db);
    }
    
    // 插入默认管理员账户的方法
    private void insertDefaultAdmin(SQLiteDatabase db) {
        ContentValues values = new ContentValues();
        values.put(COLUMN_NICKNAME, "admin");
        values.put(COLUMN_PASSWORD, "admin");
        values.put(COLUMN_IS_VIP, 1); // 默认设置为VIP
        values.put(COLUMN_COINS, 9999); // 设置初始金币
        values.put(COLUMN_CREATE_TIME, System.currentTimeMillis());
        
        db.insert(TABLE_USERS, null, values);
    }
} 